/****************************************************************************
** Шаблонизатор (выделение информации с веб-ресурсов)
** Быков И.И.
** 07.06.2013
****************************************************************************/
#include "Mainwindow.h"

#include "ProxyDialog.h"
#include "SaveDialog.h"
#include "ConnectionSettings.h"
#include "Templater.h"
#include "TemplateViewer.h"

#include "Findwidget.h"

#include "BookmarksDialog.h"
#include "BookmarksManager.h"
#include "BookmarksMenu.h"
#include "AddBookmarkDialog.h"
#include "BookmarksDockWidget.h"

#include "SettingsDialog.h"

#include "Passwords.h"

#include <QtGui>
#include <QtNetwork>
#include <QtWebKit>
#include <QIcon>
#include <QPalette>

//! [1]

MainWindow::MainWindow(const QUrl& url) :
    m_template_loaded(false) ,
    progress(0)
{
    setWindowIcon(QIcon(":icons/templater.png"));

//! [1]
    QNetworkProxyFactory::setUseSystemConfiguration(true);

//! [2]
    view = new TemplateViewer(this);
    view->load(url);
    connect(view, SIGNAL(loadFinished(bool)), SLOT(adjustLocation()));
    connect(view, SIGNAL(titleChanged(QString)), SLOT(adjustTitle()));
    connect(view, SIGNAL(loadProgress(int)), SLOT(setProgress(int)));
    connect(view, SIGNAL(loadFinished(bool)), SLOT(finishLoading(bool)));

    locationEdit = new QLineEdit(this);
    locationEdit->setSizePolicy(QSizePolicy::Expanding, locationEdit->sizePolicy().verticalPolicy());
    connect(locationEdit, SIGNAL(returnPressed()), SLOT(changeLocation()));
    connect(view, SIGNAL(linkClicked( const QUrl)), this, SLOT(setLocationUrl( const QUrl)));
    connect(view, SIGNAL(urlChanged(const QUrl)), this, SLOT(setLocationUrl( const QUrl)));
//! [2]

    setupToolBar();
    setupMenu();

//! [3]
    QVBoxLayout *layout = new QVBoxLayout;
    layout->setSpacing(0);
    layout->setMargin(0);

    layout->addWidget(view);

    setUnifiedTitleAndToolBarOnMac(true);

    createTestDockWidget();
    createFieldDockWidget();
    createBookmarksDockWidget();

    findWidget = new FindWidget(this);
    layout->addWidget(findWidget);
    findWidget->setSizePolicy( QSizePolicy::Fixed, QSizePolicy::Fixed );
    findWidget->hide();

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);

    connect(findWidget, SIGNAL(findNext()), this, SLOT(slotEditFindNext()));
    connect(findWidget, SIGNAL(findPrevious()), this, SLOT(slotEditFindPrevious()));
    connect(findWidget, SIGNAL(find(QString, bool)), this, SLOT(find(QString, bool)));

    m_templater = new Templater;
//! [3]
    QTimer::singleShot(0, this, SLOT(setSettings()));
}

void MainWindow::setupToolBar()
{
    // Navigation Bar
    QToolBar *nav_toolBar = addToolBar(tr("Навигация"));
    nav_toolBar->addAction(view->pageAction(QWebPage::Back));
    nav_toolBar->addAction(view->pageAction(QWebPage::Forward));
    nav_toolBar->addAction(view->pageAction(QWebPage::Reload));
    nav_toolBar->addAction(view->pageAction(QWebPage::Stop));

    nav_toolBar->addWidget(locationEdit);

    m_marker = new QAction(QIcon(":icons/label.png"), "Привязать к метке", this);
    m_marker->setCheckable(true);
    nav_toolBar->addAction(m_marker);
    connect( m_marker, SIGNAL(toggled(bool)), this, SLOT(markerElements(bool)) );

    m_tmplt = new QAction(QIcon(":icons/add_frame.png"), "Разметить страницу", this);
    m_tmplt->setCheckable(true);
    nav_toolBar->addAction(m_tmplt);
    connect( m_tmplt, SIGNAL(toggled(bool)), this, SLOT(frameElements(bool)) );

    m_save = new QAction(QIcon(":icons/save.png"), "Сохранить шаблон", this );
    nav_toolBar->addAction(m_save);
    connect( m_save, SIGNAL(triggered()), this, SLOT(saveTemplate()) );

    m_settings = new QAction( QIcon(":icons/settings.png"), "Настройки", this );
    nav_toolBar->addAction(m_settings);
    connect( m_settings, SIGNAL(triggered()), this, SLOT(settings()) );
}

void MainWindow::setSettings()
{
    QString directory = QDesktopServices::storageLocation(QDesktopServices::DataLocation);
    if (directory.isEmpty())
        directory = QDir::homePath() + QLatin1String("/.") + QCoreApplication::applicationName();
    QWebSettings::setIconDatabasePath(directory);
    QWebSettings::setOfflineStoragePath(directory);
}

void MainWindow::setupMenu()
{
    // File Menu
    QMenu *fileMenu = menuBar()->addMenu(tr("&Файл"));
    fileMenu->addAction(QIcon(":icons/file_open.png"), "Открыть страницу...", this, SLOT(openHTML()), QKeySequence(tr("Ctrl+o")));
    fileMenu->addAction(QIcon(":icons/file_save.png"), "Сохранить страницу как...", this, SLOT(saveHTML()), QKeySequence(tr("Ctrl+s")));

    // Edit Menu
    QMenu *editMenu = menuBar()->addMenu(tr("&Правка"));
    editMenu->addSeparator();

    // Edit Menu -- Find
    QAction* m_find = new QAction(tr("&Найти"), this);
    m_find->setIcon( QIcon(":icons/find.png") );
    m_find->setShortcuts( QKeySequence::Find );
    connect(m_find, SIGNAL(triggered()), this, SLOT(slotEditFind()));
    editMenu->addAction( m_find );
    this->addAction( m_find );

    // Edit Menu -- Find Next
    QAction* m_findNext = new QAction(tr("&Найти следующее"), this);
    m_findNext->setIcon( QIcon(":icons/find_next.png") );
    m_findNext->setShortcuts(QKeySequence::FindNext);
    connect(m_findNext, SIGNAL(triggered()), this, SLOT(slotEditFindNext()));
    editMenu->addAction( m_findNext );
    this->addAction( m_findNext );

    // Edit Menu -- Find Previous
    QAction* m_findPrevious = new QAction(tr("&Найти предыдущее"), this);
    m_findPrevious->setIcon( QIcon(":icons/find_previous.png") );
    m_findPrevious->setShortcuts(QKeySequence::FindPrevious);
    connect(m_findPrevious, SIGNAL(triggered()), this, SLOT(slotEditFindPrevious()));
    editMenu->addAction( m_findPrevious );
    this->addAction( m_findPrevious );

    // View Menu
    QMenu *viewMenu = menuBar()->addMenu(tr("&Вид"));
    QAction* actionEncoding = new QAction(tr("Кодировка"), this);
    m_menuEncoding = new QMenu(this);
    actionEncoding->setMenu(m_menuEncoding);
    connect(m_menuEncoding, SIGNAL(aboutToShow()), this, SLOT(slotShowEncodingMenu()));
    viewMenu->addAction(actionEncoding);

    // Bookmarks Menu
    m_bookmarksManager = new BookmarksManager;
    BookmarksMenu *bookmarksMenu = new BookmarksMenu(m_bookmarksManager, this);
//    connect(bookmarksMenu, SIGNAL(openUrl(const QUrl&)), m_tabWidget, SLOT(loadUrlInCurrentTab(const QUrl&)));
//    connect(bookmarksMenu, SIGNAL(hovered(const QString&)), this, SLOT(slotUpdateStatusbar(const QString&)));
    bookmarksMenu->setTitle(tr("&Закладки"));
    menuBar()->addMenu(bookmarksMenu);

    // Bookmarks Menu -- Show All Bookmarks
    QAction *showAllBookmarksAction = new QAction( tr("Показать все закладки"), this);
    connect(showAllBookmarksAction, SIGNAL(triggered()), this, SLOT(slotShowBookmarksDialog()));
    showAllBookmarksAction->setIcon( QIcon((":icons/all_bookmarks.png")) );
    showAllBookmarksAction->setShortcut( QKeySequence(Qt::CTRL + Qt::Key_B) );
    this->addAction( showAllBookmarksAction );

    // Add Bookmark
    m_addBookmark = new QAction(tr("Добавить закладку..."), this);
    m_addBookmark->setIcon(	QIcon(":icons/add_bookmark.png") );
    connect(m_addBookmark, SIGNAL(triggered()), this, SLOT(slotAddBookmark()));
    m_addBookmark->setShortcut( QKeySequence(Qt::CTRL | Qt::Key_D));
    this->addAction(m_addBookmark);

    QList<QAction*> bookmarksActions;

    bookmarksActions.append(showAllBookmarksAction);
    bookmarksActions.append(m_addBookmark);
    bookmarksMenu->setInitialActions(bookmarksActions);

    // View Menu
    QMenu *toolsMenu = menuBar()->addMenu(tr("&Инструменты"));
    toolsMenu->addAction(m_marker);
    toolsMenu->addAction(m_tmplt);
    toolsMenu->addAction(m_save);
    toolsMenu->addSeparator();
    toolsMenu->addAction(m_settings);

    // Settings Menu
    QMenu *settingsMenu = menuBar()->addMenu(tr("&Опции"));
    settingsMenu->addAction(QIcon(":icons/file_open.png"), "Пароли",
                  this, SLOT(slotShowPasswords()), QKeySequence(tr("Ctrl+P")));
    settingsMenu->addAction(QIcon(":icons/settings.png"), "Настройки",
                  this, SLOT(slotSettings()), QKeySequence(tr("Ctrl+L")));

}

//! [4]
void MainWindow::adjustLocation()
{
    locationEdit->setText(view->url().toString());
}

void MainWindow::changeLocation()
{
    QString page = locationEdit->text();
    QUrl url = QUrl( completeURL(page) );

    view->load(url);
    view->setFocus();
}
//! [4]

//! [5]
void MainWindow::adjustTitle()
{
    if (progress <= 0 || progress >= 100)
        setWindowTitle(view->title());
    else
        setWindowTitle(QString("Context Mining [%1 (%2%)]").arg(view->title()).arg(progress));
}

void MainWindow::setProgress(int p)
{
    progress = p;
    adjustTitle();
}
//! [5]

//! [6]
void MainWindow::finishLoading(bool)
{
    progress = 100;
    adjustTitle();
    view->applyJQuery();
}
//! [6]

//! [9]
void MainWindow::createTestDockWidget()
{
    QDockWidget *dockWidget = new QDockWidget("Проверка", this);

    QPushButton *btn_template = new QPushButton(QIcon(":icons/template.png"), "Загрузить шаблон");
    QPushButton *btn_curr = new QPushButton(QIcon(":icons/down.png"), "Текущий шаблон");
    QPushButton *btn_start = new QPushButton(QIcon(":icons/start.png"), "Старт");
    label_template_name = new QLabel("Шаблон: Нет");
    label_template_name->setStyleSheet( QString("font: italic 8pt \"MS Shell Dlg 2\";") );

    connect( btn_template, SIGNAL(clicked()), this, SLOT( loadTemplate() ) );
    connect( btn_curr, SIGNAL(clicked()), this, SLOT( setCurrentTemplate() ) );
    connect( btn_start, SIGNAL(clicked()), this, SLOT( startTemplate() ) );

    QHBoxLayout *startLayout = new QHBoxLayout;
    startLayout->addWidget(btn_template);
    startLayout->addWidget(btn_curr);
    startLayout->addWidget(btn_start);
    startLayout->addWidget(label_template_name);
    startLayout->setAlignment ( Qt::AlignLeft );

    m_edit_result = new QTextEdit();
    QVBoxLayout *vlayot = new QVBoxLayout();
    vlayot->addLayout(startLayout);
    vlayot->addWidget(m_edit_result);

    QWidget *widget = new QWidget();
    widget->setLayout(vlayot);

    dockWidget->setWidget(widget);
    addDockWidget(Qt::BottomDockWidgetArea, dockWidget);
}

void MainWindow::createFieldDockWidget()
{
    QDockWidget *dockWidget = new QDockWidget("Поля", this);

    QPushButton *btn_update = new QPushButton(QIcon(":icons/update.png"), "Обновить");
    connect( btn_update, SIGNAL(clicked()), this, SLOT( updatePathTable() ) );

    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->addWidget(btn_update);
    hLayout->setAlignment ( Qt::AlignLeft );

    m_table = new QTableWidget(0, 5, this);
    m_table->setSelectionBehavior(QAbstractItemView::SelectRows);

    QStringList icons;
    icons << ":icons/number.png" << ":icons/label.png" << ":icons/key.png"
          << ":icons/value.png" << ":icons/path.png";
    int i = 0;
    foreach(QString icon, icons)
    {
        QTableWidgetItem* item = new QTableWidgetItem();
        item->setIcon(*(new QIcon(icon)));
        m_table->setHorizontalHeaderItem(i,item);
        i++;
    }

    QStringList headerLabels;
    headerLabels << " Номер" << " Метка" << " Ключ" << " Значение" << " Путь";
    m_table->setHorizontalHeaderLabels(headerLabels);

    i = 0;
    foreach(QString label, headerLabels)
    {
        m_table->horizontalHeaderItem(i)->setTextAlignment(Qt::AlignLeft);
        i++;
    }

    QVBoxLayout *vlayot = new QVBoxLayout();
    vlayot->addLayout(hLayout);
    vlayot->addWidget(m_table);

    QWidget *widget = new QWidget();
    widget->setLayout(vlayot);

    dockWidget->setWidget(widget);
    addDockWidget(Qt::BottomDockWidgetArea, dockWidget);
}

void MainWindow::createBookmarksDockWidget()
{
    BookmarksDockWidget *dockWidget = new BookmarksDockWidget(m_bookmarksManager, this);
    connect(dockWidget, SIGNAL(openUrl(const QUrl&)), this, SLOT(slotLoadUrl(const QUrl&)));
    addDockWidget(Qt::RightDockWidgetArea, dockWidget);
}

QString MainWindow::completeURL(const QString &page)
{
    QString complete_page;
    QUrl url = QUrl(page);
    if ( QFile::exists(page) && url.isValid() )
        return page;

    if ( page.indexOf("http://www.") == 0 || page.indexOf("https://www.") == 0 )
        return page;

    if ( page.indexOf("http://") == 0 || page.indexOf("https://") == 0 )
        return page;

    complete_page = "http://www." + page;
    QUrl complete_url = QUrl(complete_page);
    if ( complete_url.isValid() )
        return complete_page;

    return page;
}
//! [9]

/// TODO
void MainWindow::frameElements(bool state)
{
    if (state && m_marker->isChecked()) m_marker->setChecked(false);
    view->highlight(state);
}

void MainWindow::markerElements(bool state)
{
    if (state && m_tmplt->isChecked()) m_tmplt->setChecked(false);

    QFile file;
    file.setFileName("highlight_marker.js");
    file.open(QIODevice::ReadOnly);
    QString code = file.readAll();
    file.close();

    QString ret = view->page()->mainFrame()->evaluateJavaScript(code).toString();
    m_edit_result->append(ret);
}

void MainWindow::settings()
{
    ProxyDialog dlg(this);
    if ( dlg.exec() == QDialog::Accepted )
    {
        ConnectionSettings settings = dlg.value();
        connectionSettingsToXML("cnct.xml", settings);
        if (settings.useProxy)
            setProxy(settings);
    }
}

void MainWindow::saveTemplate()
{
    QUrl url = QUrl(locationEdit->text());
    SaveDialog dlg(url.host(), this);
    if ( dlg.exec() == QDialog::Accepted )
    {
        QString filter = dlg.filter();
        m_templater->setFilter(filter);

        QString fileName = QFileDialog::getSaveFileName(this, tr("Укажите имя файла шаблона"), QString(),
                                                        "*.tm", 0, 0);
        m_templater->setFileName(fileName);

        QStringList paths = view->pathList();
        PathList pathList;
        foreach (QString xpath, paths)
        {
            PathInfo pi;
            pi.key = "Инфо";
            pi.path = xpath;
            pathList << pi;
        }

        m_templater->setPathList( pathList );

        m_templater->save();

        m_template_loaded = true;
    }
}

void MainWindow::openHTML()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Выберите страницу"), QString(),
                                                    "*.html;*.htm", 0, 0);
    if (fileName.isEmpty())
        return;

    view->load( QUrl::fromLocalFile(fileName) );
    view->setFocus();
}

void MainWindow::saveHTML()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Сохранить страницу"), view->title(),
                                                    "*.htm", 0, 0);

    QTextCodec *codec = QTextCodec::codecForName( view->pageCodecName().toStdString().c_str() );

    QString content = view->page()->mainFrame()->toHtml();

    QFile file(fileName);
    if (!file.open(QIODevice::WriteOnly))
        return;
    QTextStream stream(&file);
    stream.setCodec(codec);

    stream << content;
    stream.flush();
}

void MainWindow::setProxy(const ConnectionSettings &settings)
{
    QNetworkProxy proxy;

    proxy.setType( settings.useProxy ? QNetworkProxy::HttpProxy : QNetworkProxy::NoProxy);
    if (settings.useProxy)
    {
        proxy.setHostName( settings.proxy_addres );
        proxy.setPort( settings.proxy_port );
        proxy.setUser(settings.user);
        proxy.setPassword(settings.pass);
    }

    QNetworkProxy::setApplicationProxy(proxy);
}

void MainWindow::loadTemplate()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Укажите файл шаблона"), QString(),
                                                    "*.tm", 0, 0);
    if (fileName.isEmpty())
        return;

    m_templater->setFileName(fileName);
    m_templater->load();

    QFileInfo fi(fileName);

    label_template_name->setText( QString("Шаблон: %1  для доменных имен %2")
                                  .arg(fi.fileName())
                                  .arg(m_templater->filter()) );
    label_template_name->setToolTip(fileName);
    m_template_loaded = true;
}

void MainWindow::setCurrentTemplate()
{
    if (!m_template_loaded)
    {
        QMessageBox::warning(this, "Установка текущего шаблона", "Шаблон не создан");
        return;
    }

    QFileInfo fi(m_templater->fileName());
    label_template_name->setText( QString("Шаблон: %1  для доменных имен %2")
                                  .arg(fi.fileName())
                                  .arg(m_templater->filter()) );
}

void MainWindow::updatePathTable()
{
    m_table->setRowCount(0);

    QStringList paths = view->pathList();
    PathList pathList;
    foreach (QString xpath, paths)
    {
        PathInfo pi;
        pi.key = "Инфо";
        pi.path = xpath;
        pathList << pi;
    }
    m_templater->setPathList( pathList );

    foreach (PathInfo info, pathList)
    {
        int row = m_table->rowCount();
        m_table->insertRow(row);

        m_table->setItem(row,0,new QTableWidgetItem(QString::number(row)));
        m_table->setItem(row,1,new QTableWidgetItem("Отсутствует"));
        m_table->setItem(row,2,new QTableWidgetItem(info.key));
        m_table->setItem(row,3,new QTableWidgetItem(view->pathValue(info.path)));
        m_table->setItem(row,4,new QTableWidgetItem(info.path));
    }

    m_table->resizeColumnsToContents();
}

void MainWindow::startTemplate()
{
    if (!m_template_loaded)
    {
        QMessageBox::warning(this, "Запуск шаблона", "Шаблон не выбран");
        return;
    }
    if (!locationEdit->text().toLower().contains( m_templater->filter().toLower() ))
    {
        int r = QMessageBox::question(this, "Запуск шаблона",
                             QString("Текущий URL : %1\nФильтр текущего шаблона: %2\n"
                             "\nURL не подходит по фильтру.\n\nВсе равно применить шаблон?").arg(locationEdit->text()).arg(m_templater->filter()),
                             QMessageBox::Yes|QMessageBox::Default,
                             QMessageBox::No|QMessageBox::Escape);
        if (r != QMessageBox::Yes)
            return;
    }

    QFileInfo fi(m_templater->fileName());
    m_edit_result->append(QString("<font color = #336600>Запуск шаблона из файла: %1 </font>")
                          .arg(fi.fileName()));
    m_edit_result->append(QString("<font color = #336600>Фильтр: %1 </font>")
                          .arg(m_templater->filter()));

    foreach(PathInfo pathInfo, m_templater->pathList())
    {
        QString value = view->pathValue(pathInfo.path);
        if (value.isEmpty()) continue;
        m_edit_result->append(QString("<font color = #3300FF>%1</font> : <font color = #CC3300>%2</font>").arg(pathInfo.key).arg(value));
    }
    m_edit_result->append("<font color = #999999>******************************</font>");
    m_edit_result->append("");
}

void MainWindow::setLocationUrl(const QUrl &url)
{
    qDebug()<<"linkClicked" << url<< url.scheme();
    //view->load(url);
    locationEdit->setText( url.toString() );
}

// Find

void MainWindow::slotEditFind()
{
    findWidget->show();
}

void MainWindow::find(const QString &ttf, bool forward)
{
    bool found = false;

    QWebPage::FindFlags options;
    if ( !ttf.isEmpty() )
    {
        if (!forward)
            options |= QWebPage::FindBackward;

        if (findWidget->caseSensitive())
            options |= QWebPage::FindCaseSensitively;

        found = view->findText(ttf, options);
        findWidget->setTextWrappedVisible(false);

        if (!found)
        {
            options |= QWebPage::FindWrapsAroundDocument;
            found = view->findText(ttf, options);
            if (found)
                findWidget->setTextWrappedVisible(true);
        }
    }

    // force highlighting of all other matches, also when empty (clear)
    options = QWebPage::HighlightAllOccurrences;
    if (findWidget->caseSensitive())
        options |= QWebPage::FindCaseSensitively;
    view->findText(QLatin1String(""), options);
    view->findText(ttf, options);

    // the line edit is empty, no need to mark it red...
    if (!found && ttf.isEmpty())
        found = true;

    if (!findWidget->isVisible())
        findWidget->show();

    findWidget->setPalette(found);
}

void MainWindow::slotEditFindNext()
{
    find(findWidget->text(), true);
}

void MainWindow::slotEditFindPrevious()
{
    find(findWidget->text(), false);
}

void MainWindow::slotShowBookmarksDialog()
{
    BookmarksDialog *dialog = new BookmarksDialog(this, m_bookmarksManager);
    connect(dialog, SIGNAL(openUrl(const QUrl&)), this, SLOT(slotLoadUrl(const QUrl&)));
    dialog->show();
}

void MainWindow::slotAddBookmark()
{
    QString url = view->url().toString();
    QString title = view->title();

    QSettings settings;
    settings.beginGroup(QLatin1String("websettings"));
    bool bUseDefaultLocation = settings.value(QLatin1String("addBookmarkUseDefaultLocation"), false).toBool();
    QString defaultLocation = settings.value(QLatin1String("addBookmarkDefaultLocation"), "").toString();

    AddBookmarkDialog dialog(url, title, (bUseDefaultLocation ? defaultLocation : ""), m_bookmarksManager);
    if (bUseDefaultLocation)
        dialog.acceptDefaultLocation();
    else
        dialog.exec();
}

void MainWindow::slotShowPasswords()
{
    Passwords *dialog = new Passwords(this);
    dialog->exec();
    delete dialog;
}

void MainWindow::slotSettings()
{
    SettingsDialog *s = new SettingsDialog(this);
    s->show();
}

void MainWindow::slotLoadUrl(const QUrl &url, const QString &)
{
    locationEdit->setText( url.toString() );
    view->load(url);
    view->setFocus();
}

void MainWindow::slotShowEncodingMenu()
{
    m_menuEncoding->clear();
    QMenu* menuISO = new QMenu("ISO", this);
    QMenu* menuUTF = new QMenu("UTF", this);
    QMenu* menuWindows = new QMenu("Windows", this);
    QMenu* menuIscii = new QMenu("Iscii", this);
    QMenu* menuOther = new QMenu(tr("Other"), this);

    QList<QByteArray> available = QTextCodec::availableCodecs();
    qSort(available);
    const QString &activeCodec = "UTF-8";/*mApp->webSettings()->defaultTextEncoding()*/

    foreach (const QByteArray &name, available) {
        QTextCodec* codec = QTextCodec::codecForName(name);
        if (codec && codec->aliases().contains(name)) {
            continue;
        }

        const QString nameString = QString::fromUtf8(name);

        QAction* action = new QAction(nameString, 0);
        action->setData(nameString);
        action->setCheckable(true);
        connect(action, SIGNAL(triggered()), this, SLOT(changeEncoding()));
        if (activeCodec.compare(nameString, Qt::CaseInsensitive) == 0) {
            action->setChecked(true);
        }

        if (nameString.startsWith(QLatin1String("ISO"))) {
            menuISO->addAction(action);
        }
        else if (nameString.startsWith(QLatin1String("UTF"))) {
            menuUTF->addAction(action);
        }
        else if (nameString.startsWith(QLatin1String("windows"))) {
            menuWindows->addAction(action);
        }
        else if (nameString.startsWith(QLatin1String("Iscii"))) {
            menuIscii->addAction(action);
        }
        else if (nameString == QLatin1String("System")) {
            m_menuEncoding->addAction(action);
        }
        else {
            menuOther->addAction(action);
        }
    }

    m_menuEncoding->addSeparator();
    if (!menuISO->isEmpty()) {
        m_menuEncoding->addMenu(menuISO);
    }
    if (!menuUTF->isEmpty()) {
        m_menuEncoding->addMenu(menuUTF);
    }
    if (!menuWindows->isEmpty()) {
        m_menuEncoding->addMenu(menuWindows);
    }
    if (!menuIscii->isEmpty()) {
        m_menuEncoding->addMenu(menuIscii);
    }
    if (!menuOther->isEmpty()) {
        m_menuEncoding->addMenu(menuOther);
    }
}

void MainWindow::changeEncoding(QObject* obj)
{
    if (!obj)
        obj = sender();

    if (QAction* action = qobject_cast<QAction*>(obj))
    {
        const QString &encoding = action->data().toString();
//        mApp->webSettings()->setDefaultTextEncoding(encoding);

//        Settings settings;
//        settings.setValue("Web-Browser-Settings/DefaultEncoding", encoding);

//        reload();
    }
}
